const express = require('express')
const router = express.Router()
const {
    insertOrder,
    getOrderList,
    getOrderDetail,
    modifyOrderState,
    getCheckedShopCartlist,
    getOrderByState,
    updateProductSalesAndStore,
    modifyShopCartState,
    removeCheckedShopCartList,
    updateProductListState,
    getProductDetail
} = require('../../model/mongo')

router.get('/list', async (req, res) => {
    let { userid } = req.query
    let result = {
        code: 200,
        msg: '获取订单列表'
    }
    result.data = await getOrderList(userid)
    res.send(JSON.stringify(result))
})

router.get('/statelist', async (req, res) => {
    let { userid, state } = req.query
    let result = {
        code: 200,
        msg: '获取不同状态下订单'
    }
    result.data = await getOrderByState(userid, Number(state))
    res.send(JSON.stringify(result))
})

router.get('/detail', async (req, res) => {
    let { orderid } = req.query
    let result = {
        code: 200,
        msg: '获取订单详情',
    }
    result.data = await getOrderDetail(orderid)
    res.send(JSON.stringify(result))
})

router.post('/add', lack, async (req, res) => {
    let { userid, proid, addressid, count, size } = req.body
    let result = {
        code: 200,
        msg: '添加订单成功'
    }
    result.orderid = await insertOrder(userid, addressid, proid, count, size)
    result.store = await updateProductSalesAndStore(proid, count)
    res.send(JSON.stringify(result))
})

router.put('/confirm', async (req, res) => {
    let { orderid } = req.body
    let result = {
        code: 200,
        msg: '确认收货'
    }
    result.data = await modifyOrderState(orderid, 2)
    res.send(JSON.stringify(result))
})

router.put('/back', async (req, res) => {
    let { orderid } = req.body
    let result = {
        code: 200,
        msg: '退货申请'
    }
    result.data = await modifyOrderState(orderid, 3)
    res.send(JSON.stringify(result))
})

router.get('/checklist', async (req, res) => {
    let { userid } = req.query
    let result = {
        code: 200,
        msg: '获取购物车中选中订单列表'
    }
    result.data = await getCheckedShopCartlist(userid)
    res.send(JSON.stringify(result))
})

router.post('/addchecked', lacks, async (req, res) => {
    let { userid, addressid, isLack, cartlist } = req.body
    let result = {
        code: 200,
        msg: '购物车下单成功'
    }
    let insertAll = []
    cartlist = cartlist.map(item => {
        const insert = insertOrder(userid, addressid, item.proid, item.num, item.size || 'xl')
        item.stock === item.num ? updateProductListState(item.proid, 'issale', false) : ''
        updateProductSalesAndStore(item.proid, item.num)
        insertAll.push(insert)
    })
    Promise.all(insertAll).then(resolve => {
        result.proids = resolve
        removeCheckedShopCartList(userid).then(suc => {
            if (isLack) {
                result.msg = '部分缺货商品没有下单'
            }
            res.send(JSON.stringify(result))
        }).catch(err => {
            result.code = 400
            result.msg = '购物车没清空'
            res.send(JSON.stringify(result))
        })
    }).catch(err => {
        result.code = 400
        result.proids = []
        res.send(JSON.stringify(result))
    })
})

// 用户下单缺货验证-中间件
async function lack (req, res, next) {
    let { proid, count } = req.body
    const pro = await getProductDetail(proid)
    if (pro.stock === Number(count)) {
        // 将它及时调整为下架
        await updateProductListState(proid, 'issale', false)
    }
    pro.stock >= count ? next() : res.send(JSON.stringify({
        code: 200,
        msg: '库存不足，只剩' + pro.stock + '件'
    }))
}

// 用户购物车下单批量缺货验证-中间件
async function lacks (req, res, next) {
    let { userid } = req.body
    let cartlist = await getCheckedShopCartlist(userid)
    let lackList = cartlist.filter(item => item.stock < item.num || !item.issale)

    for (let i = 0; i < lackList.length; i++) {
        let { cartid, proid } = lackList[i]
        await modifyShopCartState(cartid, false)
    }

    req.body.cartlist = cartlist.filter(item => item.issale && item.stock >= item.num)
    lackList.length ? req.body.isLack = true : req.body.isLack = false
    next()
}

module.exports = router
